package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import entity.MyFile;
import util.DBHelp;
import util.RowMapper;

public class MyFileDao {
	
	DBHelp<MyFile> db = new DBHelp<MyFile>();
	
	public int addFile(MyFile myFile){
		String sql = "insert into bmw_file (showname, name ,bmw_user_id, bmw_folder_id, size) value (?,?,?,?,?)";
		return db.excuteSQL(sql, myFile.getShowName(), myFile.getName(), myFile.getUserId(), myFile.getFolderId(), myFile.getSize());
	}
	
	public List<MyFile> findByFolderId(int folderId) {
		String sql = "select bmw_file.id, showname, bmw_file.name, size , bmw_folder_id, bmw_user_id, bmw_user.name as bmw_user_name from bmw_user, bmw_file where bmw_user_id= bmw_user.id and bmw_folder_id =?";
		return db.excuteForList(sql, new FileRowMapper(), folderId);
	}
	
	public MyFile findByFileId(int id) {
		String sql = "select * from bmw_file where id = ?";
		return db.executeForObject(sql, new FindFileRowMapper(), id);
	}
	
	public List<MyFile> findByMD5(String md5) {
	    String sql = "select * from bmw_file where name like ?";
	    return db.excuteForList(sql, new FindFileRowMapper(), md5 + "%");
	}
	
	public int delFile(int id){
		String sql = "delete from bmw_file where id = ?";
		return db.excuteSQL(sql, id);
	}
	
	public int delBYFolderID(int folderId) {
		String sql = "delete from bmw_file where bmw_folder_id = ?";
		return db.excuteSQL(sql, folderId);
	}
	
	private class FileRowMapper implements RowMapper<MyFile> {

		@Override
		public MyFile mapperRow(ResultSet rs) throws SQLException {
			MyFile myFile = new MyFile();
			myFile.setId(rs.getInt("id"));
			myFile.setShowName(rs.getString("showname"));
			myFile.setName(rs.getString("name"));
			myFile.setSize(rs.getLong("size"));
			myFile.setFolderId(rs.getInt("bmw_folder_id"));
			myFile.setUserId(rs.getInt("bmw_user_id"));
			myFile.setUserName(rs.getString("bmw_user_name"));
			return myFile;
		}
	}
	
	private class FindFileRowMapper implements RowMapper<MyFile> {

		@Override
		public MyFile mapperRow(ResultSet rs) throws SQLException {
			MyFile myFile = new MyFile();
			myFile.setId(rs.getInt("id"));
			myFile.setShowName(rs.getString("showname"));
			myFile.setName(rs.getString("name"));
			myFile.setSize(rs.getLong("size"));
			myFile.setFolderId(rs.getInt("bmw_folder_id"));
			myFile.setUserId(rs.getInt("bmw_user_id"));
			return myFile;
		}
	}
}
